package com.you.raft.rpc.impl;

import com.you.raft.common.entity.AppendEntryRequest;
import com.you.raft.common.entity.ClientRequest;
import com.you.raft.common.entity.VoteRequest;
import com.you.raft.core.RaftNode;
import com.you.raft.core.impl.DefaultRaftNode;
import com.you.raft.rpc.RpcRaftServer;
import com.you.raft.common.entity.Request;
import com.you.raft.common.entity.Response;
import com.you.rpc.RpcServer;
import com.you.rpc.server.UserProcessor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class DefaultRpcServer implements RpcRaftServer {
    private final RpcServer rpcServer;
    private final RaftNode node;

    public DefaultRpcServer(int port, DefaultRaftNode node) {
        rpcServer = new RpcServer(port);
//        rpcServer.<Request>registerUserProcessor((request) -> handlerRpcRequest(request));
        rpcServer.registerUserProcessor(new UserProcessor<Request>() {
            @Override
            public Object handlerRequest(Request request) {
                return handlerRpcRequest(request);
            }
        });
        this.node = node;
    }

    @Override
    public Response<?> handlerRpcRequest(Request request) {
        int cmd = request.getCmd();
        switch (cmd) {
            case Request.VOTE:
                return new Response<>(node.handlerVoteRequest((VoteRequest) request.getObj()));
            case Request.APPEND_ENTRIES:
                return new Response<>(node.handlerAppendEntry((AppendEntryRequest) request.getObj()));
            case Request.CLIENT_ORDER:
                return new Response<>(node.handlerClientRequest((ClientRequest) request.getObj()));
            default:
                throw new RuntimeException("不存在的请求");
        }
    }

    @Override
    public void init() throws InterruptedException {
        rpcServer.start();
    }

    @Override
    public void destory() throws InterruptedException {
        rpcServer.destroy();
    }
}
